var albumId;
var albuminfo = {};
var photoListApp;
var albumObj = {};
var flag = false
$(document).ready(function () {
    //url解码
    var thisURL = document.URL;
    var getval = decodeURI(thisURL).split('?')[1].split("&");
    //url参数转换为键值对
    for (var i = 0; i < getval.length; i++) {
        var albuminfokey = getval[i].split("=")[0];
        var albuminfovalue = getval[i].split("=")[1];
        albuminfo[albuminfokey] = albuminfovalue;
    }
    //相册名称、权限赋值
    $(".albumName").text(albuminfo.albumName);
    $(".albumName").attr("title", albuminfo.albumName);
    if (albuminfo.albumpower == 0) {
        $(".albumPower").text("对外不可见");
    }
    if (albuminfo.albumpower == 1) {
        $(".albumPower").text("对外可见");
    }

    //照片列表获取
    albumId = albuminfo.albumId;

    albumObj.albumid = albumId;
    if (albumId.indexOf("#") != -1) {
        albumId = albumId.substring(0, albumId.indexOf("#"));
    }
    //vue渲染照片列表
    photoListApp = new Vue({
        el: '#photoListId',
        data: {
            photoList: [],
            remarkList: [],
            activePhoto: 0,
            activePhotoInfo: {}
        },
        created: function () {
            console.log('创建了页面')
            this.initAlbum();
        },
        methods: {
            initAlbum: function () {
                console.log($("#begin").val(),$("#end").val())
                if($("#begin").val()!=""||$("#end").val()!=""){
                    var beginDate=new Date($("#begin").val().replace("-", "/").replace("-", "/"));
                    var endDate=new Date($("#end").val().replace("-", "/").replace("-", "/"));
                    if (beginDate < endDate){
                        initAlbum($("#begin").val(), $("#end").val());
                    }else{
                        $("#begin").val("")
                        $("#end").val("")
                        layer.msg("日期范围错误，请重输！");
                    }
                }else{
                    initAlbum();
                }

            },

            showPhotoDetail: function (index) {
               
                showPhotoDetail(index);
            },
            // 选择照片，防止事件冒泡
            handleSelectIcon: function (index) {
                handleSelectIcon(index);
            },
            // 删除单张照片
            deletePhoto: function (imagePath, fileid, activePhotoIndex) {
                deletePhoto(imagePath, fileid, activePhotoIndex);
            },
            totationImage: function (fileid) {
                totationImage(fileid);
            },
            clickReply: function (remarkInfo) {
                clickReply(remarkInfo);
            },
            updatePhotoCount: function (fileid) {
                updatePhotoCount(fileid)
            }
        }
    });

    // 监听上传照片按钮
    $(document).on("click", "#uploadImg", function () {
        albuminfo.imageCount = $(".ma5-gallery figure").length;
        location.href = "uploadImg.html?albumId=" + albuminfo.albumId + "&albumName=" + albuminfo.albumName + "&albumpower=" + albuminfo.albumpower;
        localStorage.setItem("imageCount", albuminfo.imageCount);
    })
    // localStorage.setItem("albumId", albuminfo.albumId);

    //监听编辑按钮
    $(document).on("click", "#editImg", function () {
        if ($("#editImg").hasClass("layui-btn-disabled") == false) {   //批量删除按钮禁用
            $("#editImg").removeClass("layui-btn-normal").addClass("layui-btn-disabled");
        }
        $("#sureDelete").css("display", "inline-block"); //确认删除按钮显示
        $("#cancelEdit").css("display", "inline-block"); //取消删除按钮显示
        $("#selectAll").css("display", "inline-block"); //全选按钮显示
        $(".maskImg").css("display", "block");   //照片遮罩显示
        $(".selectIcon").css("display", "block");    //选中框显示
    })
    //监听全选按钮
    $(document).on("click", "#selectAll", function () {
        if ($(this).hasClass("cancelSelectAll") == true) {
            $(".selectIcon").text("");
            $(".selectIcon").removeClass("selected");
            $(this).text("全选");
            $(this).removeClass("cancelSelectAll");
        } else {
            $(".selectIcon").text("√");
            $(".selectIcon").addClass("selected");
            $(this).text("取消全选");
            $(this).addClass("cancelSelectAll");
        }
    })

    $("#meihua").click(function () {
        if (!flag) {
            $(".photoList li").addClass("frame")
            flag = true
            $("#meihua").html("取消美化")
        } else {
            flag = false
            $(".photoList li").removeClass("frame")
            $("#meihua").html("美化照片")
        }

    })

    //监听确认删除按钮
    $(document).on("click", "#sureDelete", function () {
        if ($(".selected").length == 0) {
            alert("请选择照片");
        } else {
            //获取已选择照片的id
            var imageids = [];
            var selectedImage = $(".selected");
            for (var i = 0; i < selectedImage.length; i++) {
                imageids.push(selectedImage[i].getAttribute("id"));
            }

            // 测试接口
            $.ajax({
                data: {
                    imageids: JSON.stringify(imageids)
                },
                url: "/filetransfer/deleteimagebyids",
                dataType: "json",
                type: "POST",
                async: true,
                success: function (result) {
                    if (result.success) {
                        layer.msg("删除成功", {icon: 1});
                        if ($("#editImg").hasClass("layui-btn-disabled") == true) {
                            $("#editImg").removeClass("layui-btn-disabled").addClass("layui-btn-normal");
                        }
                        $(".selectIcon").css("display", "none");
                        $("#selectAll").css("display", "none");
                        $(".maskImg").css("display", "none");
                        $("#sureDelete").css("display", "none");
                        $("#cancelEdit").css("display", "none");
                        //删除photoList中的数组元素
                        for (var j = 0; j < imageids.length; j++) {
                            for (var k = 0; k < photoListApp.photoList.length; k++) {
                                if (imageids[j] == photoListApp.photoList[k].imageid) {
                                    photoListApp.photoList.splice(k, 1);
                                    break;
                                }
                            }
                        }
                        // $(".selected").parent().parent().remove();
                        $(".photoCount").text(photoListApp.photoList.length + "张 /");
                        if (photoListApp.photoList.length == 0) {
                            $(".photoShowGallery").html("<span class='emptyAlbum'>相册为空</span>");
                            $(".photoCount").text("0张 /");
                            $("#editImg").css("display", "none");
                        }
                        initAlbum()
                    } else {
                        layer.msg(result.errorMessage, {icon: 2});
                    }
                },
                error: function () {
                    //alert("系统繁忙!");
                }
            });
        }
    })
    //监听取消编辑按钮
    $(document).on("click", "#cancelEdit", function () {
        $(this).css("display", "none");
        if ($("#editImg").hasClass("layui-btn-disabled") == true) {
            $("#editImg").removeClass("layui-btn-disabled").addClass("layui-btn-normal");
        }
        $(".selectIcon").css("display", "none");
        $(".maskImg").css("display", "none");
        $("#selectAll").css("display", "none");
        $("#sureDelete").css("display", "none");

        $(".selectIcon").text("");
        $(".selectIcon").removeClass("selected");
        $("#selectAll").text("全选");
        $("#selectAll").removeClass("cancelSelectAll");
    })

    // 获取用户头像
    function getUserHeadImg() {
        var userHeadImgUrl = $("#head-nav-img").attr("src");
        $(".userHeadImg").attr("src", userHeadImgUrl);
    }

});

/**
 * 冒泡事件处理
 * @param param
 */
function handleSelectIcon(param) {
    if ($(".selectIcon")[param].innerText != "") {   //选中框内添加√
        $(".selectIcon")[param].innerText = "";
        $(".selectIcon")[param].classList.remove("selected");
    } else {
        $(".selectIcon")[param].innerText = "√";
        $(".selectIcon")[param].classList.add("selected");
    }
    if ($(".selected").length == $(".selectIcon").length) {
        $("#selectAll").text("取消全选");
        $("#selectAll").addClass("cancelSelectAll");
    }
}

/**
 * 向右旋转图片 90度
 * @param imageid
 */
function totationImage(imageid) {
    var imageInfo = {
        direction: "right",
        imageid: imageid
    };
    $.ajax({
        data: imageInfo,
        url: "/filetransfer/totationimage",
        dataType: "json",
        type: "POST",
        async: true,
        success: function (result) {
            if (result.success) {
                photoListApp.initAlbum();
                photoListApp.showPhotoDetail(photoListApp.activePhoto);
            } else {
                alert(result.errorMessage);
            }
        },
        error: function () {
            //alert("系统繁忙!");
        }
    });
}

/**
 * 删除图片
 * @param imagePath 图片路径
 * @param imageid 图片id
 * @param activePhotoIndex
 */
function deletePhoto(imagePath, imageid, activePhotoIndex) {
    var imageInfo = {
        imageurl: imagePath,
        imageid: imageid
    };
    $.ajax({
        data: imageInfo,
        url: "/filetransfer/deleteimage",
        dataType: "json",
        type: "POST",
        async: true,
        success: function (result) {
            if (result.success) {
                layer.msg("删除成功", {icon: 1})
                // 关闭轮播图，照片列表中删除相应元素
                $(".swiperWrapper").css("display", "none");
                $(".photoList").children(".list-item")[activePhotoIndex].style.display = "none";
            } else {
                layer.msg(result.errorMessage, {icon: 2})
            }
        },
        error: function () {
            //alert("系统繁忙!");
        }
    });
}

function updatePhotoCount(fileid) {
    var imageInfo = {
        fileid: fileid
    };
    $.ajax({
        data: imageInfo,
        url: "/file/primarirycount",
        dataType: "json",
        type: "POST",
        async: true,
        success: function (result) {
            if (result.success) {
                layer.msg("点赞成功", {icon: 1})
                window.location.reload()
            } else {
                layer.msg(result.errorMessage, {icon: 2})
            }
        },
        error: function () {
            //alert("系统繁忙!");
        }
    });
}

/**
 * 展示图片大图（swiper）
 * @param index
 */
function showPhotoDetail(index) {
    photoListApp.activePhoto = index;
    //模板引擎渲染轮播图
    $(".swiperWrapper").css("display", "block");
    $(".imgListWrapper").html(
        template("swiperTemplate", {
            list: photoListApp.photoList
        })
    );
    //轮播图
    var galleryThumbs = new Swiper('.gallery-thumbs', {
        spaceBetween: 10,
        slidesPerView: 7,
        freeMode: true,
        watchSlidesVisibility: true,
        watchSlidesProgress: true
    });
    var galleryTop = new Swiper('.gallery-top', {
        keyboard: true,
        spaceBetween: 10,
        initialSlide: photoListApp.activePhoto, //设定初始化时slide的索引
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev'
        },
        pagination: {
            el: '.swiper-pagination',
            type: 'fraction'
        },
        thumbs: {
            swiper: galleryThumbs
        },
        observer: true,//修改swiper自己或子元素时，自动初始化swiper
        observeParents: true,//修改swiper的父元素时，自动初始化swiper,
        on: {
            init: function () { //Swiper初始化时，赋值照片信息展示区域
                photoListApp.activePhotoInfo = photoListApp.photoList[this.activeIndex];
                currentShowImageInfo = photoListApp.photoList[this.activeIndex];
                showRemark(currentShowImageInfo.fileid);
            },
            slideChangeTransitionEnd: function () { //切换结束时，修改照片信息展示区域
                photoListApp.activePhotoInfo = photoListApp.photoList[this.activeIndex];
                currentShowImageInfo = photoListApp.photoList[this.activeIndex];
                showRemark(currentShowImageInfo.fileid);
            },
        },
    });
    // 监听退出按钮
    $(document).on("click", ".exitButton", function () {
        $(".swiperWrapper").css("display", "none");
    });

    $("#navbottomBarId").hide()
}

function initAlbum(begin, end) {
    $.ajax({
        url: "/file/getimagelistbyalbum",
        dataType: "json",
        data: {
            begin: begin,
            end: end,
            albumid: albumObj.albumid
        },
        type: "POST",
        success: function (result) {
            if (result.success == false) {
                // layer.msg("相册为空", {icon: 2})
                $(".photoList").hide()
                photoListApp.photoList.length = 0
                $(".photoShowGallery").append("<span class='emptyAlbum'>相册为空</span>")
            } else {
                if(result.data.length!=0){
                    $(".photoList").show()
                    $(".emptyAlbum").remove();
                    photoListApp.photoList = result.data;
                }else {
                    photoListApp.photoList.length = 0
                    $(".photoShowGallery").append("<span class='emptyAlbum'>相册为空</span>")
                    $(".photoList").hide()
                }


            }
        },
        error: function (result) {
            //alert("系统繁忙!");
        }
    });
}

function deleteCurrentImage() {
    var imagePath = document.getElementsByClassName("ma5-clone")[0].getAttribute("src");
    var id = document.getElementsByClassName("ma5-clone")[0].getAttribute("id");

    var imageInfo = {
        fileurl: imagePath,
        fileid: id
    };
    $.ajax({
        data: imageInfo,
        url: "/filetransfer/deleteimage",
        dataType: "json",
        type: "POST",
        async: true,
        success: function (result) {
            if (result.success) {
                layer.msg("删除成功", {icon: 1})
                window.location.href = "showalbum.html?albumId=" + albumId;
            } else {
                layer.msg(result.errorMessage, {icon: 2})
            }
        },
        error: function () {
            //alert("系统繁忙!");
        }
    });
}

//添加评论
function remarkConfirm() {
    var remarkContent = document.getElementById("remarkInputId").value;
    if (remarkContent.trim() == "") {
        alert("内容为空");
    }
    if (!currentShowImageInfo) {
        currentShowImageInfo = photoListApp.photoList[0];
    }
    var essayJson = {};
    essayJson["targetid"] = currentShowImageInfo.fileid;
    essayJson["remarkContent"] = remarkContent;
    essayJson["modulename"] = "album";

    $.ajax({
        data: essayJson,
        url: "/remark/addremark",
        dataType: "json",
        type: "POST",
        success: function (result) {
            if (result.success) {
                showRemark(currentShowImageInfo.fileid);
                document.getElementById("remarkInputId").value = ""
            } else {
                alert(result.errorMessage);
            }
        },
        error: function (result) {
            alert("系统繁忙!");
        }
    });
}

//显示评论内容
function showRemark(fileid) {
    var essayJson = {};
    essayJson["targetid"] = fileid;
    essayJson["modulename"] = "album";
    $.ajax({
        data: essayJson,
        url: "/remark/getremarkcontent",
        dataType: "json",
        type: "get",
        success: function (result) {
            if (result.success) {
                photoListApp.remarkList = result.data;

            } else {
                alert(result.errorMessage);
            }
        },
        error: function (result) {
            //alert("系统繁忙!");
        }
    });

}


function clickReply(remarkInfo) {
    var username;
    var userId;
    var remarkedId;
    if (remarkInfo.essayId != null) {
        username = remarkInfo.userBean.username;
        userId = remarkInfo.userBean.userId;
        remarkedId = remarkInfo.remarkId;
    } else {
        username = remarkInfo.repliedUserName;
        userId = remarkInfo.repliedUserId;
        remarkedId = remarkInfo.remarkedId;
    }
    var repliedUserObj = {};
    repliedUserObj["repliedUserId"] = userId;
    repliedUserObj["repliedUserName"] = username;
    repliedUserObj["remarkedId"] = remarkedId;
    layer.prompt({
        formType: 2,
        placehold: "回复" + username,
        title: '回复',
        area: ['420px', '200px'] //自定义文本域宽高
    }, function (value, index, elem) {

        if (value.trim() == "") {
            // alert("内容为空");
            layer.msg("内容为空", {icon: 2})
        } else {
            repliedUserObj["replyContent"] = value;
            $.ajax({
                data: repliedUserObj,
                url: "/remark/addreply",
                dataType: "json",
                type: "POST",
                success: function (result) {
                    if (result.success) {
                        layer.msg("成功", {icon: 1})
                        showRemark(currentShowImageInfo.fileid)
                    } else {
                        layer.msg(result.errorMessage, {icon: 2})
                    }
                },
                error: function (result) {
                    layer.msg("系统繁忙", {icon: 2})
                }
            });
        }

        layer.close(index);
    });

}
